#!/bin/bash
function uninit()
{
    echo -ne "\a"
    rm -rf $w
    echo
}

function downscale()
{
    INPUT="$1"
    SUBTITLE="$2"    
    SUBTITLE_DEL="$3"    
    OUTPUT="$4"
#    mplayer -vc null -af volume=15.1:1 -ao pcm:fast:file=$w/snd.wav -vo null  "$INPUT" &> /dev/null& 
#    P1=$!
    ffmpeg -i "$INPUT" -b 64 -vol 650 -vn -acodec aac $w/$OUTPUT.mp4 &
#    faac -w -o $w/$OUTPUT.mp4 --obj-type LC $w/snd.wav 
    P2=$!
    if [ -z "$TURBO" ] ;  then
	mencoder   ${SUBTITLE_DEL:+-subdelay "$SUBTITLE_DEL"}  ${SUBTITLE:+-sub "$SUBTITLE"} -profile $PROFILE -nosound -o $w/$OUTPUT.avi "$INPUT"
    else
	echo Root password
	sudo renice -12 -p $P2
	sudo nice -n -17 mencoder ${SUBTITLE:+-sub "$SUBTITLE"} -profile $PROFILE -nosound -o $w/OUTPUT.avi "$I"
    fi
    wait
}

. ./params

echo ${PROFILE:=k800}
trap uninit EXIT

w=$(mktemp -d)
mkfifo $w/snd.wav

downscale "$I1" "$S1" "$D1" out1
if [ -n "$I2" ] ; then
    downscale "$I2" "$S2" "$D2" out2
fi    

if [ -n "$I2" ] ; then
    MP4Box -add $w/out1.mp4 -cat $w/out2.mp4 -add $w/out1.avi  -cat $w/out2.avi "$w/out.mp4"
else
    MP4Box -add $w/out1.mp4 -add $w/out1.avi  "$w/out.mp4"
fi

if [ ${O:0:1} == "#" ] ; then
    ln -sf "$w/out.mp4" "$w/${O:1}"
    obexftp -u 0 -p "$w/${O:1}"
else
    mv -f "$w/out.mp4" $O
fi


